const http = require("http");
const fs = require("fs");
const { URL } = require("url");
const path = require("path");
http.createServer((req, res) => {
    let urlObj = new URL(req.url, "http://localhost:3000/")
    let pathName = urlObj.pathname;
    if (pathName == '/') {
        let fileContent = fs.readFileSync("./upload.html");
        //res响应字符串 buffer
        res.writeHead(200, { "Content-type": "text/html;charset=utf8" });
        res.end(fileContent);
    }
    else if (pathName == "/upload") {
        let str = "";
        //数据进入
        req.setEncoding("binary");
        req.on("data", (chunk) => {
            str += chunk;
        })
        req.on("end", () => {
            fs.writeFileSync("log.txt", str)

            let arr = str.split("\r\n");
            arr = arr.slice(4);
            let imgStr = arr.join("\r\n");
            let filePath = path.join(__dirname, "/upload/2.png")
            // let imgBuf = Buffer.from(imgStr, "binary")
            //windows
            // fs.writeFileSync("./upload/1.png", imgStr, { "encoding": "binary" });
            //数据写入
            //linux windows
            fs.writeFileSync(filePath, imgStr, { "encoding": "binary" });
            res.end(JSON.stringify({ "status": "ok" }))
        })
    }
}).listen(3000);

console.log("server is listening 3000");